import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

const CredentialDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [credential, setCredential] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('overview'); // overview, subject, json

  useEffect(() => {
    const fetchCredential = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await walletApi.getCredential(id);
        if (response.success) {
          setCredential(response.credential);
        } else {
          setError(response.error || '获取凭证失败');
        }
      } catch (error) {
        console.error('获取凭证详情出错:', error);
        setError('获取凭证详情时发生错误，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchCredential();
  }, [id]);

  // 计算凭证状态
  const getCredentialStatus = (credential) => {
    const now = new Date();
    if (credential.revoked) {
      return { status: 'revoked', text: '已撤销' };
    } else if (credential.expirationDate && new Date(credential.expirationDate) < now) {
      return { status: 'expired', text: '已过期' };
    } else {
      return { status: 'active', text: '有效' };
    }
  };

  if (loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">加载中...</span>
        </div>
      </div>
    );
  }

  if (error || !credential) {
    return (
      <div className="alert alert-danger">
        {error || '找不到凭证'}
        <button 
          className="btn btn-outline-danger ms-3"
          onClick={() => navigate('/wallet/credentials')}
        >
          返回凭证列表
        </button>
      </div>
    );
  }

  const credStatus = getCredentialStatus(credential);

  return (
    <div className="credential-detail">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">凭证详情</h4>
        <button
          className="btn btn-outline-secondary"
          onClick={() => navigate('/wallet/credentials')}
        >
          <i className="bi bi-arrow-left me-2"></i>
          返回列表
        </button>
      </div>

      <div className="card mb-4">
        <div className="card-body">
          <div className="d-flex justify-content-between align-items-start mb-3">
            <h3>
              {credential.credential.type 
                ? (Array.isArray(credential.credential.type) 
                    ? (credential.credential.type.length > 1 
                ? credential.credential.type[credential.credential.type.length - 1]
                        : credential.credential.type[0])
                    : (typeof credential.credential.type === 'string' 
                        ? credential.credential.type 
                        : JSON.stringify(credential.credential.type)))
                : '未知类型'}
            </h3>
            <span className={`status-badge ${credStatus.status}`}>
              {credStatus.text}
            </span>
          </div>

          <div className="row mb-4">
            <div className="col-md-6">
              <div className="mb-3">
                <small className="text-muted">凭证ID:</small>
                <p className="mb-0 text-break">{credential.id}</p>
              </div>
              <div className="mb-3">
                <small className="text-muted">发行方:</small>
                <p className="mb-0 text-break">{credential.credential.issuer}</p>
              </div>
            </div>
            <div className="col-md-6">
              <div className="mb-3">
                <small className="text-muted">发行日期:</small>
                <p className="mb-0">
                  {new Date(credential.credential.issuanceDate).toLocaleString()}
                </p>
              </div>
              <div className="mb-3">
                <small className="text-muted">过期日期:</small>
                <p className="mb-0">
                  {credential.credential.expirationDate 
                    ? new Date(credential.credential.expirationDate).toLocaleString() 
                    : '永不过期'}
                </p>
              </div>
            </div>
          </div>

          <div className="d-grid gap-2 d-md-flex justify-content-md-center mb-4">
            <button
              className="btn btn-primary"
              onClick={() => navigate(`/wallet/proofs?credentialId=${credential.id}`)}
            >
              <i className="bi bi-shield-check me-1"></i> 生成证明
            </button>
            <button
              className="btn btn-outline-secondary"
              onClick={() => {
                const jsonString = JSON.stringify(credential.credential, null, 2);
                navigator.clipboard.writeText(jsonString);
                alert('凭证JSON已复制到剪贴板');
              }}
            >
              <i className="bi bi-clipboard me-1"></i> 复制JSON
            </button>
          </div>

          <ul className="nav nav-tabs">
            <li className="nav-item">
              <button
                className={`nav-link ${activeTab === 'overview' ? 'active' : ''}`}
                onClick={() => setActiveTab('overview')}
              >
                概览
              </button>
            </li>
            <li className="nav-item">
              <button
                className={`nav-link ${activeTab === 'subject' ? 'active' : ''}`}
                onClick={() => setActiveTab('subject')}
              >
                凭证主体
              </button>
            </li>
            <li className="nav-item">
              <button
                className={`nav-link ${activeTab === 'json' ? 'active' : ''}`}
                onClick={() => setActiveTab('json')}
              >
                JSON
              </button>
            </li>
          </ul>

          <div className="tab-content pt-3">
            {activeTab === 'overview' && (
              <div className="tab-pane active">
                <h5 className="mb-3">凭证信息</h5>
                <div className="table-responsive">
                  <table className="table table-striped">
                    <tbody>
                      <tr>
                        <th style={{ width: '30%' }}>类型</th>
                        <td>
                          {credential.credential.type 
                            ? (Array.isArray(credential.credential.type)
                            ? credential.credential.type.join(', ')
                                : (typeof credential.credential.type === 'string'
                                    ? credential.credential.type
                                    : JSON.stringify(credential.credential.type)))
                            : '未知'}
                        </td>
                      </tr>
                      {credential.credential.credentialStatus && (
                        <tr>
                          <th>状态信息</th>
                          <td>
                            <div><strong>类型:</strong> {credential.credential.credentialStatus.type}</div>
                            {credential.credential.credentialStatus.id && (
                              <div><strong>ID:</strong> {credential.credential.credentialStatus.id}</div>
                            )}
                            {credential.credential.credentialStatus.statusListCredential && (
                              <div>
                                <strong>状态列表:</strong> {credential.credential.credentialStatus.statusListCredential}
                              </div>
                            )}
                          </td>
                        </tr>
                      )}
                      <tr>
                        <th>上下文</th>
                        <td>
                          {credential.credential['@context'] && Array.isArray(credential.credential['@context'])
                            ? credential.credential['@context'].map((ctx, i) => <div key={i}>{ctx}</div>)
                            : credential.credential['@context'] || '未知'}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {credential.credential.proof && (
                  <div className="mt-4">
                    <h5 className="mb-3">证明信息</h5>
                    <div className="table-responsive">
                      <table className="table table-striped">
                        <tbody>
                          <tr>
                            <th style={{ width: '30%' }}>类型</th>
                            <td>{credential.credential.proof.type || '未知'}</td>
                          </tr>
                          {credential.credential.proof.created && (
                            <tr>
                              <th>创建日期</th>
                              <td>{new Date(credential.credential.proof.created).toLocaleString()}</td>
                            </tr>
                          )}
                          {credential.credential.proof.verificationMethod && (
                            <tr>
                              <th>验证方法</th>
                              <td>{credential.credential.proof.verificationMethod}</td>
                            </tr>
                          )}
                          {credential.credential.proof.proofPurpose && (
                            <tr>
                              <th>证明目的</th>
                              <td>{credential.credential.proof.proofPurpose}</td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'subject' && (
              <div className="tab-pane active">
                <h5 className="mb-3">凭证主体</h5>
                {credential.credential.credentialSubject ? (
                  <div className="table-responsive">
                    <table className="table table-striped">
                      <tbody>
                        {Object.entries(credential.credential.credentialSubject).map(([key, value]) => (
                          <tr key={key}>
                            <th style={{ width: '30%' }}>{key}</th>
                            <td>
                              {typeof value === 'object'
                                ? JSON.stringify(value, null, 2)
                                : String(value)}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div className="alert alert-warning">无凭证主体数据</div>
                )}
              </div>
            )}

            {activeTab === 'json' && (
              <div className="tab-pane active">
                <h5 className="mb-3">原始JSON</h5>
                <div className="bg-light p-3 rounded">
                  <pre className="mb-0" style={{ overflowX: 'auto' }}>
                    {JSON.stringify(credential.credential, null, 2)}
                  </pre>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CredentialDetail; 